package com.itmayiedu.api.service.impl;

import com.feign.OrderServiceFeign;
import com.itmayiedu.api.service.PayOrderService;
import com.itmayiedu.base.BaseApiService;
import com.itmayiedu.base.ResponseBase;
import com.itmayiedu.constants.Constants;
import com.itmayiedu.dao.PaymentInfoDao;
import com.itmayiedu.entity.PaymentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author cht 【wonderfor@vip.qq.com】
 * @Date 2018/11/8
 */
@RestController
public class PayOrderServiceImpl extends BaseApiService implements PayOrderService {

    @Autowired
    private OrderServiceFeign orderServiceFeign;

    @Autowired
    private PaymentInfoDao paymentInfoDao;

    @Override
    @Transactional
    public String payOrder(@RequestParam("orderId") String orderId, @RequestParam("temp") int temp) {
        PaymentInfo paymentInfo = paymentInfoDao.getByOrderIdPayInfo(orderId);
        if(paymentInfo == null) {
            return Constants.PAY_FAIL;
        }
        //支付宝重试机制为并行
        Integer state = paymentInfo.getState();
        if(state == 1) {
            return Constants.PAY_SUCCESS;
        }
        //支付宝交易号
        String tradeNo = "644064779";
        //修改支付状态
        paymentInfo.setState(1);//标识为已支付
        paymentInfo.setPayMessage("test");
        paymentInfo.setPlatformorderId(tradeNo);

        Integer result = paymentInfoDao.updatePayInfo(paymentInfo);
        if(result <= 0) {
            return Constants.PAY_FAIL;
        }
        //调用订单接口
        ResponseBase orderResult = orderServiceFeign.updateOrder(1l, tradeNo, orderId);
        if(!orderResult.getRtnCode().equals(Constants.HTTP_RES_CODE_200)) {
            //回滚 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
            return Constants.PAY_FAIL;
        }
        int i = 1/temp;
        return Constants.PAY_SUCCESS;
    }

}
